﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using RedeSocial.ViewModels;
using RedeSocial.ViewModels.Interfaces;
using RedeSocial.DataAccess;
using RedeSocial.Validation;
using Telerik.Web.UI;

namespace RedeSocial.Web.UserControls
{
	public partial class AddFile : BaseUserControl
	{
		#region overrides...
		protected override void CreateViewModel()
		{
			CreateUserViewModel = new CreateUserViewModel()
			{
				DefaultLanguage = Session["DefaultLanguage"] as Language,
				FluentValidator = new CreateUserValidator((Session["DefaultLanguage"] as Language).Id)
			};
			if (!IsPostBack)
			{
				using (var dataContext = new RedeSocialEntities())
				{
				}
			}
		}
		protected override void BindViewModel()
		{

		}
		protected override void BindLabels()
		{
			CreateUserViewModel.DefaultLanguage = Session["DefaultLanguage"] as Language;
			//lblError.Text = ResourceManager.GetResource(Constants.LOGINVIEW_INVALIDUSERMESSAGE, LoginViewModel.DefaultLanguage.Id);
		}
		#endregion
		#region properties...
		protected CreateUserViewModel CreateUserViewModel
		{
			get
			{
				return ViewModel as CreateUserViewModel;
			}
			set
			{
				ViewModel = value;
			}
		}
		#endregion
		#region event handles...
		protected void Page_Load(object sender, EventArgs e)
		{
			Response.Cache.SetCacheability(HttpCacheability.NoCache);
			if (!IsPostBack)
			{
			}
		}
		#endregion

		protected void RadButton1_Click(object sender, EventArgs e)
		{
			ContenType contentType;
			using (var context = new RedeSocialEntities())
			{
				foreach (UploadedFile item in RadUpload1.UploadedFiles)
				{
					contentType = context.ContenTypes.Where(c => c.Name.Equals(item.ContentType, StringComparison.CurrentCultureIgnoreCase)).FirstOrDefault();
					if (contentType == null)
						contentType = new ContenType() { Name = item.ContentType };
					byte[] fileBytes = new byte[item.ContentLength];
					if (item.InputStream.Read(fileBytes, 0, fileBytes.Length) > 0)
						context.Files.Add(new File()
						{
							ContenType = contentType,
							Description = item.FileName.Substring(item.FileName.LastIndexOf('\\') + 1),
							Object = fileBytes
						});
				}
				context.SaveChanges();
			}
		}
	}
}